<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 按钮 -->
            <el-row class="addButton">
                <el-col>
                    <el-button type="primary" @click="addRole">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表区域 -->
            <el-table :data="roleList" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <!-- 渲染一级权限 -->
                        <el-row v-for="(item,i) in scope.row.children" :key="item.id" :class="['bdbottom',i?'':'bdtop','vcenter']">
                            <el-col :span="5">
                                <el-tag closable @close="removeRoleRights(scope.row,item.id)">{{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <el-row v-for="(item1,i1) in item.children" :key="item1.id" :class="[i1?'bdtop':'','vcenter']">
                                    <el-col :span="6">
                                        <el-tag type="success"  closable @close="removeRoleRights(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="item2 in item1.children" :key="item2.id" closable @close="removeRoleRights(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRoleDialog(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delate" @click="deleteRole(scope.row)">删除</el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRoleRights(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色Dialog对话框 -->
        <el-dialog
        title="添加角色"
        :visible.sync="addRoleVisible"
        width="30%"
        @close="addRoleFormClosed">
        <el-form :model="addRoleForm" :rules="addRoleFomeRules" ref="addRoleFomeRef" label-width="80px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRoleForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addRoleVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRoleInfo">确 定</el-button>
        </span>
        </el-dialog>
        <!-- 编辑角色对话框 -->
        <el-dialog
        title="编辑角色"
        :visible.sync="editRoleFormVisible"
        width="30%">
        <el-form :model="editRoleForm" :rules="addRoleFomeRules" ref="editRoleFormRef" label-width="80px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="editRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="editRoleForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editRoleFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRoleInfo">确 定</el-button>
        </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog
        title="分配权限"
        :visible.sync="setRoleFormVisible"
        width="30%">
        <!-- 树形控件 -->
        <el-tree :data="rightsList" :props="treeProps" ref="treeRef" show-checkbox node-key='id' default-expand-all :default-checked-keys="defKeys"></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRoleFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="allRoleRights">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data () {
    return {
      // 所有角色列表
      roleList: [],
      // 添加角色对话框控制
      addRoleVisible: false,
      // 编辑角色对话框控制
      editRoleFormVisible: false,
      //   添加角色表单
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色表单
      editRoleForm: {},
      // 添加角色表单验证规则
      addRoleFomeRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述信息', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 分配权限对话框
      setRoleFormVisible: false,
      // 权限列表
      rightsList: [],
      // 树形控件属性绑定
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认勾选的数组
      defKeys: [],
      roleId: ''
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    //   获取角色列表
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色信息失败')
      this.roleList = res.data
      console.log(this.roleList)
    },
    // 弹出添加角色对话框
    addRole () {
      this.addRoleVisible = true
    },
    // 添加角色
    addRoleInfo () {
      this.$refs.addRoleFomeRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.addRoleVisible = false
        this.$message.success('添加成功')
        this.getRoleList()
      })
    },
    // 重置添加角色对话框
    addRoleFormClosed () {
      this.$refs.addRoleFomeRef.resetFields()
    },
    // 弹出编辑角色对话框
    async editRoleDialog (value) {
      const { data: res } = await this.$http.get('roles/' + value.id)
      if (res.meta.status !== 200) return this.$message.error('获取角色信息失败')
      this.editRoleForm = res.data
      this.editRoleFormVisible = true
    },
    // 修改角色信息并提交
    editRoleInfo () {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editRoleForm.roleId, {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.editRoleFormVisible = false
        this.getRoleList()
        this.$message.success('修改成功')
      })
    },
    // 删除角色
    async deleteRole (value) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') return this.$message.info('以取消删除')
      const { data: res } = await this.$http.delete('roles/' + value.id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 取消角色指定权限
    async removeRoleRights (role, rightsId) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
      if (res.meta.status !== 200) this.$message.error('删除权限失败')
      role.children = res.data
    },

    // 分配权限管理
    async setRoleRights (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) this.$message.error('权限获取失败')
      this.defKeys = []
      this.rightsList = res.data
      this.filterRights(role, this.defKeys)
      this.setRoleFormVisible = true
    },
    // 筛选三级权限递归
    filterRights (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        return this.filterRights(item, arr)
      })
    },
    // 分配权限
    async allRoleRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.setRoleFormVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.el-tag {
    margin: 7px
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
